class Solution {
public:
    static constexpr int MAX_N = int(1E5) + 5;

    vector <int> g[MAX_N];
    int apple[MAX_N], ans;

    int getAppleNumber(int o, int from, vector<bool>& hasApple) {
        apple[o] = hasApple[o];
        for (const auto &son: g[o]) {
            if (son == from) {
                continue;
            }
            apple[o] += getAppleNumber(son, o, hasApple);
        } 
        return apple[o];
    }

    void dfs(int o, int from) {
        for (const auto &son: g[o]) {
            if (son == from) {
                continue;
            }
            if (apple[son]) {
                ans += 2;
                dfs(son, o);
            }
        }
    }

    int minTime(int n, vector<vector<int>>& edges, vector<bool>& hasApple) {
        memset(apple, 0, sizeof apple);
        for (const auto &e: edges) {
            int u = e[0], v = e[1];
            g[u].push_back(v);
            g[v].push_back(u);
        }

        getAppleNumber(0, -1, hasApple);

        ans = 0;
        dfs(0, -1);

        return ans;
    }
};


